package com.example.zk;

import com.alibaba.fastjson.JSONObject;
import com.example.zk.configure.DataConfigure;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@SpringBootApplication
public class ZkApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZkApplication.class, args);


        /**
         * 启动zk监听
         */
        ZkClient zkClient = new ZkClient("192.168.115.129:2181");
        zkClient.subscribeDataChanges("/dataSource", new IZkDataListener() {
            /*
               节点发生改变自动
             */
            public void handleDataChange(String s, Object o) throws Exception {

                System.out.println(s+"该节点内容被更新，更新的内容"+o);
                if(o!=null){
                    System.out.println("设置数据源");
                    JSONObject jsonObject=(JSONObject)o;
                    System.out.println(jsonObject);
                    setDataConfigure(jsonObject);
                    System.out.println("设置数据源成");
                }
            }
            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s+"该节点被删除");
            }
        });


    }


    /**
     * 修改数据源
     */
    public  static void setDataConfigure(JSONObject jsonObject){
        System.out.println("进入setDataConfigure");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(jsonObject.getString("DriverClassName"));
        dataSource.setUrl(jsonObject.getString("Url"));
        dataSource.setUsername(jsonObject.getString("Username"));
        dataSource.setPassword(jsonObject.getString("Password"));
        DataConfigure.setDataConfigure(dataSource);
        System.out.println("退出setDataConfigure");
    }

}
